#!/usr/bin/env python
#
# Copyright 2005 Lukasz Strzygowski <lucass@gentoo.org>, Marcin Kurczych <tharkang@gmail.com> 
# Distributed under the terms of the GNU General Public License v2
#

"""
Submission compiler
"""

import os
from time import sleep
from tempfile import mkstemp
from django.conf import settings
from pacs.models import Submission,TestResults,GoalResults


def compile(submission):
	"""Compiles submission and puts executable in dir specified in settings, with filename equal to submission id. Adds test and goals requests."""
	print "comp"

	# removing tests and goals results connected with submission
	TestResults.objects.filter(submission=submission).delete()
	GoalResults.objects.filter(submission=submission).delete()

	# get compiler info
	comp = submission.comp

	# create temporary file and write source
	fd, src = mkstemp(suffix=".%s" % comp.extension, text=True)
	os.write(fd, submission.code)
	os.close(fd)

	# get path for executable
	dst = settings.EXECUTABLES_PATH
	if dst[-1] != '/':
		dst += '/'
	dst += str(submission.id)

	# compile
	command = comp.command % {"CODE": src, "OUT": dst}
	res = os.system(command)
	os.remove(src)

	# saves compilation status
	if res == 0:
		submission.compiled = True
	else:
		submission.compiled = False
	submission.save()

	#adds tests results requests
	if submission.compiled:
		for g in submission.task.goal_set.all():
			for t in g.tests.all():
				if TestResults.objects.filter(submission=submission,test=t).count() == 0:
					TestResults(submission=submission,test=t).save()
			GoalResults(submission=submission,goal=g).save()


if __name__ == '__main__':
	while True:
		for s in Submission.objects.filter(compiled__isnull=True):
			compile(s)
		sleep(0.1)
